package com.heima.wemedia.service.impl;

import com.heima.feign.article.IArticleClient;
import com.heima.model.comment.dtos.WmCommentManageFindDto;
import com.heima.model.comment.dtos.WmCommentManageLikeDto;
import com.heima.model.comment.dtos.WmCommentManageListDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.CommentVo;
import com.heima.model.comment.vos.WmCommentManageListVo;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.thread.WeMediaThreadLocalUtil;
import com.heima.wemedia.service.WmCommentManageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 加油, believe oneself
 * @data 2023/6/29 15:53
 */

@Slf4j
@Service
public class WmCommentManageServiceImpl implements WmCommentManageService {


    @Autowired
    private MongoTemplate mongoTemplate;



    /**
     * 展示文章评论详情
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listComments(WmCommentManageListDto dto) {
        //参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2. 是否登录
        Integer userId = WeMediaThreadLocalUtil.get();
        if (userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //根据文章id查询评论信息
        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()))
                //分页  按创建时间倒叙排序
                .skip(((dto.getPage()-1)*dto.getSize())).limit(dto.getSize())
                .with(Sort.by(Sort.Direction.DESC, "createTime"));
        //获得所有评论信息
        List<ApComment> apCommentList = mongoTemplate.find(query, ApComment.class);

        List<WmCommentManageListVo> commentRepayListVoList = new ArrayList<>();
        for (ApComment apComment : apCommentList) {
            //创建CommentRepayListVo对象封装返回信息
            WmCommentManageListVo vo = new WmCommentManageListVo();
            CommentVo commentVo=new CommentVo();
            BeanUtils.copyProperties(apComment,commentVo);
            Query query2 = Query.query(Criteria.where("commentId").is(apComment.getId()).and("authorId").is(userId));
            ApCommentLike commentLike = mongoTemplate.findOne(query2, ApCommentLike.class);
            if (commentLike==null){
                commentVo.setOperation((short)1);
            }else {
                commentVo.setOperation((short)0);
            }
            vo.setApComments(commentVo);

            //根据评论id查询评论的回复信息
            Query query1 = Query.query(Criteria.where("commentId").is(apComment.getId()))
                    //按创建时间倒叙排序
                    .with(Sort.by(Sort.Direction.DESC, "createdTime"));
            //获得所有评论的回复信息
            List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query1, ApCommentRepay.class);

            vo.setApCommentRepays(apCommentRepays);
            commentRepayListVoList.add(vo);

        }
        return ResponseResult.okResult(commentRepayListVoList);

    }


    /**
     * 点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult likeComments(WmCommentManageLikeDto dto) {
        //1. 检查参数
        if (dto == null || dto.getCommentId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2. 是否登录
        Integer userId = WeMediaThreadLocalUtil.get();
        if (userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //查询mongoDB是否有这个id
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);

        //3. 点赞
        if (dto.getOperation() == 0){
            //点赞加一
            apComment.setLikes(apComment.getLikes() + 1);
            mongoTemplate.save(apComment);

            //保存用户当前评论的记录
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setCommentId(apComment.getId());
            apCommentLike.setAuthorId(userId);
            mongoTemplate.save(apCommentLike);
        }else {
            //点赞减一
            if (apComment.getLikes() == 0){
                apComment.setLikes(0);
                mongoTemplate.save(apComment);
            }
            apComment.setLikes(apComment.getLikes() - 1);
            mongoTemplate.save(apComment);

            //删除评论点赞
            Query query = Query.query(Criteria.where("commentId").is(apComment.getId()).and("authorId").is(userId));
            mongoTemplate.remove(query, ApCommentLike.class);
        }
        //4. 取消点赞
        Map<String , Object> map = new HashMap<>();
        map.put("likes", apComment.getLikes());

        return ResponseResult.okResult(map);

    }
}
